package com.cch.platform.base.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cch.platform.base.bean.BaseUser;
import com.cch.platform.base.service.UserService;
import com.cch.platform.web.WebUtil;

@Controller
@RequestMapping(value = "/base/userlogin")
public class UserLogin {
	@Autowired
	private UserService us;

	@RequestMapping(value = "/login.do")
	public String login(HttpServletRequest request,HttpServletResponse response,ModelMap mm) {
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");
		String remPwd=request.getParameter("remPwd");
		String re="redirect:/base/index/index.jsp";
		//设置cookie
		Cookie c1=new Cookie("userName", userName);
		Cookie c2=new Cookie("userPwd", userPwd);
		c1.setMaxAge(30*24*60*60);
		c2.setMaxAge(-1);
		c1.setPath(request.getContextPath()+"/base/login/login.jsp");
		c2.setPath(request.getContextPath()+"/base/login/login.jsp");
		
		BaseUser user = us.checkUser(userName);
		if(user!=null&&user.getUserPwd().equals(userPwd)){
			request.getSession().setAttribute("user", user);
			if("on".equals(remPwd)){
				c2.setMaxAge(7*24*60*60);
			}
		}else{
			if(user==null){
				mm.put("info1", "用户不存在");
			}else{
				mm.put("info2", "密码不正确");
			}
			re="redirect:/base/login/login.jsp";
		}

		response.addCookie(c1);
		response.addCookie(c2);
		return re;
	}
	
	@RequestMapping(value = "/logout.do")
	private String logout(HttpServletRequest request,HttpServletResponse response){
		Cookie c2=new Cookie("userPwd", "xx");
		c2.setMaxAge(0);
		c2.setPath(request.getContextPath()+"/base/login/login.jsp");
		response.addCookie(c2);
		request.getSession().invalidate();
		return "redirect:/base/login/login.jsp";
	}
}
